var theType = "";

//通过ajax获取的题型生成对应的题干和选项
function getType(type) {
    theType = type;
    if (theType == "单选题" || theType == "多选题") {
        for (var i = 1; i < 5; i++) {
            createSingleChoice();
        }
    } else if (theType == "判断题") {
        for (i = 1; i < 3; i++) {
            createSingleChoice();
        }
        $("#addChoice").remove();
        $("#addChoiceH3").remove();

    } else if (theType == "填空题") {
        createFilling();
        $("#theProblem").remove();
        $("#addChoice").remove();

    } else if (theType == "问答题") {
        createSingleChoice();
        $("#addChoice").remove();
    } else {
        theType = "单选题";
        for (i = 1; i < 5; i++) {
            createSingleChoice();
        }
    }


    $("title:first").html("添加" + theType);
    $("h2:first").html("添加" + theType);
}


var stack_topleft = {"dir1": "down", "dir2": "right", "push": "top"};
function fadeTopCenter(title,msg,level) {
    $.pnotify.defaults.styling = "bootstrap3";
    var opts = {
        title: title,
        text: msg,
        closer: false,
        sticker: false,
        addclass: "stack-topleft",
        stack: stack_topleft
    };
    switch (level) {
        case 'error':
            opts.title = title;
            opts.text = msg;
            opts.type = "error";
            break;
        case 'info':
            opts.title = title;
            opts.text = msg;
            opts.type = "info";
            break;
        case 'success':
            opts.title = title;
            opts.text = msg;
            opts.type = "success";
            break;
    }
    var notice = $.pnotify(opts).click(function() {
        notice.pnotify_remove();
    });
}


//提交表单验证
function submitForm() {
    var choices = "";
    var message = "";
    var subjectText = $("#subject").val();
    if ("" == subjectText.trim()) {
        message = "&nbsp;&nbsp;请选择科目";
        fadeTopCenter('提交失败', message,'error');
        return false;
    }
    if (theType == "单选题" || theType == "多选题") {
        if ("" == $("#showProblem").html().replace(/<.[^<^>]*>/g, "").replace(/&nbsp;/g, "").trim()) {
            message = "&nbsp;&nbsp;题干为空，请填写内容";
            fadeTopCenter('提交失败', message, 'error');
            return false;
        }

        var isSubmit = 0;
        var trs = $("tr[id^='answer']");
        var choiceId = "";
        var choiceText = "";
        var flag = 0;

        for (var i = 0; i < trs.length; i++) {
            $(trs[i]).attr("id");
            choiceId = String.fromCharCode(65 + flag);
            choiceText = $("#showChoice" + choiceId).html();
            choiceText = choiceText.replace(/<p>/g, "<div>").replace(/<\/p>/g, "</div>");

            if ("" == choiceText.replace(/<.[^<^>]*>/g, "").replace(/&nbsp;/g, "").trim()) {
                message = "&nbsp;&nbsp;选项" + choiceId + "为空，请填写内容";
                fadeTopCenter('提交失败', message, 'error');
                return false;
            }

            choices = choices + "<div><span><strong>&nbsp;&nbsp;" + choiceId + ".&nbsp;&nbsp;</strong></span>" + choiceText + "</div>";
            flag++;
        }
        if (trs.length < 2) {
            message = "&nbsp;&nbsp;请添加选项";
            fadeTopCenter('提交失败', message, 'error');
            return false;
        }

        var multiAnswer = document.getElementsByName("answer");

        for (i = 0; i < multiAnswer.length; i++) {
            if (multiAnswer[i].checked) {
                isSubmit++;
            }
        }
        if (isSubmit < 1) {
            message = "&nbsp;&nbsp;请选中一个答案";
            fadeTopCenter('提交失败', message, 'error');
            return false;
        }
        if (theType == "多选题") {
            if (isSubmit < 2) {
                message = "&nbsp;&nbsp;请选中两个答案以上";
                fadeTopCenter('提交失败', message, 'error');
                return false;
            }
        }
        var theme = $("#theme").val();
        $("#theme").val(theme + "<br/>" + choices);
        return true;

    } else if (theType == "判断题") {
        if ("" == $("#showProblem").text().trim()) {
            message = "&nbsp;&nbsp;题干为空，请填写内容";
            fadeTopCenter('提交失败', message, 'error');
            return false;
        }
        return true;
    } else if (theType == "填空题") {
        theme = $("#filling").html().replace(/<\/?div.+?>|<\/div>/g, "").replace(/&nbsp;/g, "");
        var blanks = $("img[id^='blank']");
        var answerNums = $("div[id^='showChoice']");
        var fillingAnswer = "";
        var blankId = 1;
        var answers = "";

        if (answerNums.length != blanks.length) {
            message = "&nbsp;&nbsp;请删除不存在的空白项的答案";
            fadeTopCenter('提交失败', message, 'error');
            return false;
        }
        if (blanks.length < 1) {
            message = "&nbsp;&nbsp;请添加空白项";
            fadeTopCenter('提交失败', message, 'error');
            return false;
        }
        for (i = 0; i < blanks.length; i++) {
            blankId = parseInt($(blanks[i]).attr("id").replace("blank", ""));
            fillingAnswer = $("#showChoice" + blankId).text();
            answers += fillingAnswer + "、";
            if ("" == fillingAnswer.trim()) {
                message = "&nbsp;&nbsp;空白区" + blankId + "为空，请填写内容";
                fadeTopCenter('提交失败', message, 'error');
                return false;
            }

            theme = theme.replace(/<\/?.+?>/g, " _____ ");
        }
        answers = answers.substr(0, answers.length - 1);
        $("#choices").val(answers);
        $("#theme").val(theme);

        return true;
    } else if (theType == "问答题") {
        if ("" == $("#showProblem").text().trim()) {
            message = "&nbsp;&nbsp;题干为空，请填写内容";
            fadeTopCenter('提交失败', message, 'error');
            return false;
        }
        var answer = $("#showChoice1").html();
        if ("" == answer.replace(/<.[^<^>]*>/g, "").replace(/&nbsp;/g, "").trim()) {
            message = "&nbsp;&nbsp;答案为空，请填写内容";
            fadeTopCenter('提交失败', message, 'error');
            return false;
        }
        $("#choices").val(answer);
        return true;
    }


    return false;
}

//删除选项
function deleteChoice() {
    var trId = findLastTrTag();
    trId = trId.replace("answer", "");
    var flag = 1;
    if ("" != trId) {
        flag = parseInt(trId);
    }
    var key = String.fromCharCode(64 + flag);
    hideTheOtherEditor("editor" + flag, "showChoice" + key, "editTheTheme" + flag, "choice" + flag);
    $('#answer' + trId).remove();
}


var oneChoiceNum = 1;
//创建选项
function createSingleChoice() {
    var trId = findTrTag();
    var flag = oneChoiceNum;

    if (trId < 26) {
        var key = String.fromCharCode(65 + trId);
        var isChecked = "";
        if (key == "A") {
            isChecked = "checked";
        }
        var createString = "";
        if (theType == "多选题") {
            createString = "<tr id='answer" + flag + "'><td class='choicesTd'>" +
                "<div class='skin skin-square'><ul class='list'><li>" +
                "<input tabindex='" + flag + "' type='checkbox' id='square-checkbox-" + flag + "' name='answer' value='" + key + "' " + isChecked + ">" +
                "<label for='square-checkbox-" + flag + "' >&nbsp;&nbsp;" + key + "</label></li></ul></div></td>" +
                "<td><div id='showChoice" + key + "'></div><script id='editor" + flag + "' type='text/plain' style='width:500px;height:80px;'></script>" +
                "<button id='editTheTheme" + flag + "'  type='button' " +
                " style='display: none;' class='theButton'  onMouseOver=\"this.style.background='#2569c1'\" onmouseout=\"this.style.background='#114a93'\" >编辑答案</button><button class='theButton'  onMouseOver=\"this.style.background='#2569c1'\" onmouseout=\"this.style.background='#114a93'\"  id='choice" + flag + "'  type='button' " +
                ">编辑完成</button></td> </tr>";

        } else if (theType == "判断题") {
            var keyWord = "";
            if (oneChoiceNum == 1) {
                key = "T";
                keyWord = "说法正确";
                isChecked = "checked";
            } else if (oneChoiceNum == 2) {
                key = "F";
                keyWord = "说法错误";
            }

            /*            createString = "<tr id='answer" + flag + "'><td class='choicesTd'>" +
             "<input type='radio' value='" + key + "'  checked='checked'  name='answer'/>" + keyWord + "</td></tr>";*/

            createString = "<tr id='answer" + flag + "'><td class='choicesTd'>" +
                "<div class='skin skin-square'><ul class='list'><li>" +
                "<input tabindex='" + flag + "' type='radio' id='square-radio-" + flag + "' name='answer' value='" + key + "' " + isChecked + ">" +
                "<label for='square-radio-" + flag + "' >&nbsp;&nbsp;" + keyWord + "</label></li></ul></div></td></tr>";
        } else if (theType == "问答题") {
            flag = "1";
            key = "1";
            createString = "<tr id='answer" + flag + "'><td colspan='2'>" +
                "<div id='showChoice" + key + "'></div><script id='editor" + flag + "' type='text/plain' style='width:700px;height:400px;'></script>" +
                "<button id='editTheTheme" + flag + "'  type='button' " +
                " style='display: none;' class='theButton'  onMouseOver=\"this.style.background='#2569c1'\" onmouseout=\"this.style.background='#114a93'\" >编辑答案</button><button class='theButton'  onMouseOver=\"this.style.background='#2569c1'\" onmouseout=\"this.style.background='#114a93'\"  id='choice" + flag + "'  type='button' " +
                ">编辑完成</button></td> </tr>";


        } else {
            createString = "<tr id='answer" + flag + "'><td class='choicesTd'>" +
                "<div class='skin skin-square'><ul class='list'><li>" +
                "<input tabindex='" + flag + "' type='radio' id='square-radio-" + flag + "' name='answer' value='" + key + "' " + isChecked + ">" +
                "<label for='square-radio-" + flag + "' >&nbsp;&nbsp;" + key + "</label></li></ul></div></td>" +
                "<td><div id='showChoice" + key + "'></div><script id='editor" + flag + "' type='text/plain' style='width:500px;height:80px;'></script>" +
                "<button class='theButton'    onMouseOver=\"this.style.background='#2569c1'\" onmouseout=\"this.style.background='#114a93'\" id='editTheTheme" + flag + "'  type='button' " +
                " style='display: none;'>编辑答案</button><button class='theButton'  onMouseOver=\"this.style.background='#2569c1'\"  onmouseout=\"this.style.background='#114a93'\" id='choice" + flag + "'  type='button' " +
                ">编辑完成</button> </tr>";

        }


        $('#addChoice').before(createString);
        oneChoiceNum++;
        $('.skin-square input').iCheck({
            checkboxClass: 'icheckbox_square-blue',
            radioClass: 'iradio_square-blue',
            increaseArea: '10%'
        });
        if (theType != "判断题") {
            UE.getEditor('editor' + flag);
            var editTheThemeId = '#editTheTheme' + flag;
            var choiceId = '#choice' + flag;
            var showChoiceId = '#showChoice' + key;
            $(editTheThemeId).click(function () {
                showEditor("editor" + flag, "editTheTheme" + flag, "choice" + flag,"showChoice"+key);
            });
            $(showChoiceId).click(function () {
                showEditor("editor" + flag, "editTheTheme" + flag, "choice" + flag,"showChoice"+key);
            });
            $(choiceId).click(function () {
                hideTheOtherEditor("editor" + flag, "showChoice" + key, "editTheTheme" + flag, "choice" + flag);
            });

        }

    }

}

//删除填空题空白区
function deleteFilling(fillingId, blankId) {
    $(fillingId).remove();
    $(blankId).remove();

}
//创建填空题题干
function createFilling() {
    var createString = "<button class='theButton' onclick='createBlank()' type='button''>" +
        "新增一个空白区</button>(双击新空白区编辑答案)<div contenteditable='true'  style='word-break: break-all; " +
        "height:auto !important;min-height:100px;' id='filling'></div>";
    $('#theProblemH3').after(createString);

}
//创建填空题空白区
function createBlank() {
    var blank = "新空白区" + oneChoiceNum;
    var blankName = "blank" + oneChoiceNum;
    $('#filling').append("<div  style='display:inline;'> " +
        "<img id='" + blankName + "' class='blank-image' src='/img/filling.jpg'  width='110px' height='30px' style='" +
        "max-width:110px;max-height:30px;min-width:110px;min-height:30px;'  " +
        " name='" + blankName + "' title='" + blank + "' alt='" + blank + "'>" +
        "</div>");
    blankName = "#" + blankName;
    $(blankName).dblclick(function () {
        var num = parseInt(blankName.replace("#blank", ""));
        var answerTr = $("tr[id='answer" + num + "']");
        if (answerTr.length == 0) {
            createFillingAnswer(num);
        }
    });
    oneChoiceNum++;
}
//创建填空题空白区答案
function createFillingAnswer(fillingId) {
    var flag = fillingId;
    var createString = "<tr id='answer" + flag + "'><td>新空白区" + flag + "答案</td><td style='display:inline;'>" +
        "<div id='showChoice" + flag + "'></div><script id='editor" + flag + "' type='text/plain' style='width:500px;height:80px;'></script>" +
        "<button id='editTheTheme" + flag + "'  type='button' " +
        " style='display: none;' class='theButton'  onMouseOver=\"this.style.background='#2569c1'\" onmouseout=\"this.style.background='#114a93'\" >编辑答案</button><button class='theButton'  onMouseOver=\"this.style.background='#2569c1'\" onmouseout=\"this.style.background='#114a93'\"  style='margin: 5px;' id='choice" + flag + "'  type='button' " +
        ">编辑完成</button><button class='theButton'  onMouseOver=\"this.style.background='#2569c1'\" onmouseout=\"this.style.background='#114a93'\"  style='display: block;'  id='delete" + flag + "'  type='button' " +
        ">删除空白区</button></td></tr>";

    $('#subjectTd').before(createString);
    UE.getEditor('editor' + flag);
    var editTheThemeId = '#editTheTheme' + flag;
    var choiceId = '#choice' + flag;
    var deleteId = '#delete' + flag;
    var blankId = '#blank' + flag;
    var showChoiceId = '#showChoice' + flag;
    $(editTheThemeId).click(function () {
        showEditor("editor" + flag, "editTheTheme" + flag, "choice" + flag,"showChoice"+flag);
    });
    $(choiceId).click(function () {
        hideTheOtherEditor("editor" + flag, "showChoice" + flag, "editTheTheme" + flag, "choice" + flag);
    });
    $(showChoiceId).click(function () {
        showEditor("editor" + flag, "editTheTheme" + flag, "choice" + flag,"showChoice"+flag);
    });
    $(deleteId).click(function () {
        var fillingId = "#answer" + flag;
        deleteFilling(fillingId, blankId);
    });
    $("#blank" + oneChoiceNum).dblclick(function () {
    });


}

//寻找id以answer为开头的<tr>标签 ,返回数量
function findTrTag() {
    return $("tr[id^='answer']").length;
}
//获取最后一个id以answer为开头的<tr>标签
function findLastTrTag() {
    var trs = $("tr[id^='answer']");
    return $(trs[trs.length - 1]).attr("id");
}


/* 编辑器附带功能*/
function getPlainTxt() {
    var arr = [];
    arr.push(UE.getEditor('editor').getPlainTxt());
    $('#theme').val(UE.getEditor('editor').getPlainTxt());
}
function hasContent() {
    var arr = [];
    arr.push("使用editor.hasContents()方法判断编辑器里是否有内容");
    arr.push("判断结果为：");
    arr.push(UE.getEditor('editor').hasContents());
    alert(arr.join("\n"));
}
function setFocus() {
    UE.getEditor('editor').focus();
}
function isFocus(e) {
    alert(UE.getEditor('editor').isFocus());
    UE.dom.domUtils.preventDefault(e)
}
function setblur(e) {
    UE.getEditor('editor').blur();
    UE.dom.domUtils.preventDefault(e)
}


function getContent() {
    var arr = [];
    arr.push(UE.getEditor('editor').getContent());
    alert(arr.join("\n"));
}
//展开编辑框
function showEditor(editId, editTheThemeId, finishId,showChoiceId) {
    UE.getEditor(editId).show();
    $('#' + editTheThemeId).css("display", "none");
    $('#' + showChoiceId).css("display", "none");
    $('#' + finishId).css("display", "block");

}
//隐藏题干编辑框
function hideTheThemeEditor(editId) {
    $('#showProblem').css("display", "block").html(UE.getEditor(editId).getContent());
    $('#theme').val(UE.getEditor(editId).getContent());
    UE.getEditor(editId).setHide();
//    $('#editTheTheme').css("display", "block");
//    $('#finish').css("display", "none");
    $('#editTheTheme').toggle();
    $('#finish').toggle();

}
//隐藏选项编辑框
function hideTheOtherEditor(editId, showId, editTheThemeId, finishId) {
    $('#' + showId).css("display", "block").html(UE.getEditor(editId).getContent());
    UE.getEditor(editId).setHide();
//    $('#' + editTheThemeId).css("display", "block");
//    $('#' + finishId).css("display", "none");

    $('#' + editTheThemeId).toggle();
    $('#' + finishId).toggle();

}



